package burubaka.bat;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import burubaka.BurubakaConstants;
import burubaka.common.BurubakaUtil;
import burubaka.model.Handicapping;
import burubaka.model.RaceCardHorse;
import burubaka.model.RaceInfo;
import burubaka.model.Tipster;
import burubaka.service.HandicappingService;
import burubaka.service.MarkSheetService;
import burubaka.service.RaceCardHorseService;
import burubaka.service.RaceInfoService;
import burubaka.service.TipsterService;

import com.google.appengine.api.urlfetch.HTTPMethod;

/**
 * @author tk
 * 
 */
public class RegistHorseMarkBat {

	private static final Logger log = Logger.getLogger(RegistHorseMarkBat.class.getName());
	private RaceInfoService raceInfoService = new RaceInfoService();
	private RaceCardHorseService raceCardHorseService = new RaceCardHorseService();
	private TipsterService tipsterService = new TipsterService();
	private HandicappingService handicappingService = new HandicappingService();
	private MarkSheetService markSheetService = new MarkSheetService();

	public RaceInfo execute() throws Exception {

		RaceInfo raceInfo = raceInfoService.getCurrentRaceInfo();

		// すでにレース情報が登録されているかどうか判断
		// まだ登録されていない場合は何もしない
		if (raceInfo == null) {
			return null;
		}

		Tipster tipster = tipsterService.findByPost(BurubakaConstants.POST_OWNER);
		if (tipster == null) {
			return null;
		}
		Handicapping handicapping = handicappingService.getHandicapping(tipster.getKey(), raceInfo.getRaceDate());
		if (handicapping != null) {
			return null;
		}

		List<RaceCardHorse> list = raceCardHorseService.getRaceCardHorseList(raceInfo);
		if (list.size() == 0) {
			return null;
		}

		Map<RaceCardHorse, Long> markListMap = new HashMap<RaceCardHorse, Long>();

		for (RaceCardHorse raceCardHorse : list) {
			// 取消の場合は０件とする
			if (BurubakaConstants.CANCEL.equals(raceCardHorse.getMemo())) {
				markListMap.put(raceCardHorse, 0L);
				continue;
			}

			StringBuffer sb = new StringBuffer("http://google.co.jp/search?as_qdr=w1&q=");
			sb.append(BurubakaUtil.urlEncodeUTF8(raceCardHorse.getHorseName()));
			sb.append(BurubakaUtil.urlEncodeUTF8(" "));
			sb.append(BurubakaUtil.urlEncodeUTF8(raceInfo.getRaceName()));
			String text = BurubakaUtil.getURLText(sb.toString(), HTTPMethod.GET);
			String temp = BurubakaUtil.substring(">約", "件", text);
			if (temp == null) {
				temp = BurubakaUtil.substring("検索結果", "件", text);
			}
			text = temp;
			log.info(text);
			if (text == null) {
				log.info(text);
				markListMap.put(raceCardHorse, 0L);
				continue;
			}
			Long count = Long.valueOf(text.replaceAll(",", "").replaceAll("<b>", "").replaceAll("</b>", "")
					.replaceAll("約", "").trim());
			markListMap.put(raceCardHorse, count);
		}

		// ソート処理
		List<Map.Entry<RaceCardHorse, Long>> entries = new ArrayList<Map.Entry<RaceCardHorse, Long>>(
				markListMap.entrySet());
		Collections.sort(entries, new Comparator<Map.Entry<RaceCardHorse, Long>>() {
			public int compare(Map.Entry<RaceCardHorse, Long> o1, Map.Entry<RaceCardHorse, Long> o2) {
				return o2.getValue().compareTo(o1.getValue());
			}
		});

		handicapping = new Handicapping();
		handicapping.setRaceDate(raceInfo.getRaceDate());
		handicapping.setRaceName(raceInfo.getRaceName());
		handicapping.setPayOffFlag(BurubakaConstants.FLAG_ON);
		int i = 0;
		for (Map.Entry<RaceCardHorse, Long> entry : entries) {
			RaceCardHorse raceCardHorse = entry.getKey();
			if (i == 0) {
				handicapping.setHorseNo1(Integer.parseInt(raceCardHorse.getHorseNo()));
				handicapping.setHorseName1(raceCardHorse.getHorseName());
			}
			if (i == 1) {
				handicapping.setHorseNo2(Integer.parseInt(raceCardHorse.getHorseNo()));
				handicapping.setHorseName2(raceCardHorse.getHorseName());
			}
			if (i == 2) {
				handicapping.setHorseNo3(Integer.parseInt(raceCardHorse.getHorseNo()));
				handicapping.setHorseName3(raceCardHorse.getHorseName());
			}
			if (i == 3) {
				handicapping.setHorseNo4(Integer.parseInt(raceCardHorse.getHorseNo()));
				handicapping.setHorseName4(raceCardHorse.getHorseName());
			}
			if (i == 4) {
				handicapping.setHorseNo5(Integer.parseInt(raceCardHorse.getHorseNo()));
				handicapping.setHorseName5(raceCardHorse.getHorseName());
			}
			if (i == 5) {
				handicapping.setHorseNo6(Integer.parseInt(raceCardHorse.getHorseNo()));
				handicapping.setHorseName6(raceCardHorse.getHorseName());
			}
			i++;
		}

		handicappingService.regist(handicapping, tipster.getKey());
		markSheetService.registMarkSheet(tipster);

		return null;
	}

}
